﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BingImages
{
    public class MainDraw
    {
        private const int SPI_SETDESKWALLPAPER = 20;
        private const int SPIF_UPDATEINIFILE = 0x01;
        private const int SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        private mainForm _mainForm;
        private FlowLayoutPanel _flpPicture;
        private ComboBox _cbxNumberPicture;
        private Settings _settings = null;
        private Folder _folder;
        private static PictureBox[] pbxPicture;
        private static Button[] btnPicture;

        public MainDraw(mainForm mainForm)
        {
            this._mainForm = mainForm;
            this._flpPicture = this._mainForm.getFlpPicture();
            this._cbxNumberPicture = this._mainForm.getCbxNumberPicture();            
            this._folder = this._mainForm.folder;
        }

        public void setDraw()
        {
            this.init();
            FileInfo[] files = null;
            int totalFiles = 0;
            int cbxPicture = 0;
            int num = 0;
            int max = 0;
            int iObject = 0;

            this._settings = this._mainForm.settings;
            this._flpPicture.Controls.Clear();

            files = this._folder.getFiles("wallpaper", "*.jpg");
            totalFiles = files.Length - 1;
            cbxPicture = int.Parse(this._cbxNumberPicture.Text);

            if (cbxPicture > totalFiles)
            {
                max = files.Length;
            }
            else
            {
                max = cbxPicture;
            }

            pbxPicture = new PictureBox[max];
            btnPicture = new Button[max];

            for (num = 0; num < max; num++)
            {
                iObject = totalFiles - num;

                pbxPicture[num] = new PictureBox();
                pbxPicture[num].Size = new Size(86, 75);
                pbxPicture[num].BackgroundImage = new Bitmap(files[iObject].FullName);
                pbxPicture[num].BackgroundImageLayout = ImageLayout.Stretch;
                pbxPicture[num].Tag = iObject;
                pbxPicture[num].MouseEnter += new EventHandler(pbxPicture_MouseEnter);

                btnPicture[num] = new Button();
                btnPicture[num].Location = new Point(60, 3);
                btnPicture[num].Image = new Bitmap(Properties.Resources.wallpaper);
                btnPicture[num].AutoSize = true;
                btnPicture[num].AutoSizeMode = AutoSizeMode.GrowAndShrink;
                btnPicture[num].Tag = iObject;
                btnPicture[num].Click += btnPicture_Click;

                pbxPicture[num].Controls.Add(btnPicture[num]);
                this._flpPicture.Controls.Add(pbxPicture[num]);
            }
        }

        public void init()
        {
            if (pbxPicture != null)
            {
                foreach (PictureBox pbx in pbxPicture)
                {
                    pbx.BackgroundImage.Dispose();
                    pbx.BackgroundImage = null;
                }

                pbxPicture = null;
            }

            if (btnPicture != null)
            {
                foreach (Button btn in btnPicture)
                {
                    btn.Image.Dispose();
                    btn.Image = null;
                }

                btnPicture = null;
            }
        }

        public void redraw(string destFolderPath)
        {
            if (this._folder.exist(destFolderPath))
            {
                string targetPath = "";

                FileInfo[] rootFiles = this._folder.getFiles(new DirectoryInfo(this._folder.last), "*.png");

                foreach (FileInfo file in rootFiles)
                {
                    targetPath = Path.Combine(destFolderPath, Path.GetFileNameWithoutExtension(file.Name) + ".jpg");

                    if (!File.Exists(targetPath))
                    {
                        using (var image = Image.FromFile(file.FullName))
                        {
                            var newWidth = (int)(image.Width);
                            var newHeight = (int)(image.Height);
                            var thumbnailImg = new Bitmap(newWidth, newHeight);
                            var thumbGraph = Graphics.FromImage(thumbnailImg);
                            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                            thumbGraph.DrawImage(image, imageRectangle);
                            targetPath = Path.Combine(destFolderPath, targetPath);
                            thumbnailImg.Save(targetPath, image.RawFormat);
                        }
                    }
                }
            }
        }

        #region EVENTS
        private void btnPicture_Click(object sender, EventArgs e)
        {
            FileInfo[] files = null;
            string path = "";
            Image picture = null;
            string tempPath = "";
            RegistryKey key = null;

            int iNum = (int)((Button)sender).Tag;

            if (this._settings.pathExist())
            {
                path = Environment.ExpandEnvironmentVariables(this._settings.path);
                files = this._folder.getFiles(new DirectoryInfo(path), "*.png");
            }
            else
            {
                files = this._folder.getFiles(new DirectoryInfo(this._folder.last), "*.png");
            }

            picture = Image.FromFile(Path.GetFullPath(files[iNum].FullName));
            tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
            picture.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp);

            key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            key.SetValue(@"WallpaperStyle", 2.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());

            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
            picture.Dispose();
        }

        private void pbxPicture_MouseEnter(object sender, EventArgs e)
        {
            this._flpPicture.Focus();
        }
        #endregion
    }
}
